<?php

/*  
==================================================================
1. RAPEL
==================================================================
*/

function list_rapel(){
	my_set_code_js('
		function confirmDelete(id){
			var t = confirm(\'Yakin akan menghapus data ?\');
			if(t){
				location.href=\'index.php?com='.$_GET['com'].'&task=rapel_delete&id=\'+id;
			}
			return false;
		}
	');

	$header = array(
		'Sumber Transaksi'=>array('style'=>'border-bottom:2px solid;width:20%'),   
		'Referensi'=>array('style'=>'text-align:left;border-bottom:2px solid;width:40%'),   
		'Rapel'=>array('style'=>'text-align:right;border-bottom:2px solid;width:30%'),   
		' '=>array('style'=>'border-bottom:2px solid;width:10%'), 
	);

	$query = "SELECT * FROM pr_rapel 
		ORDER BY rapel_id DESC";
	$result = my_query($query );
	$total_records = my_num_rows($result );
	$scroll_page =5;  
	$per_page =25;  
	$current_page = isset($_GET['page']) ? (int) $_GET['page'] : 1 ; 
	if($current_page < 1){
		$current_page = 1;
	}		 
	$pager_url  ="index.php?com={$_GET['com']}&task={$_GET['task']}&field={$_GET['field']}&key={$_GET['key']}&page=";	 
	$inactive_page_tag = 'style="padding:4px;background-color:#BBBBBB"';  
	$previous_page_text = ' Mundur '; 
	$next_page_text = ' Maju ';  
	$first_page_text = ' Awal '; 
	$last_page_text = ' Akhir ';
	
	$kgPagerOBJ = new kgPager();
	$kgPagerOBJ->pager_set(
		$pager_url, 
		$total_records, 
		$scroll_page, 
		$per_page, 
		$current_page, 
		$inactive_page_tag, 
		$previous_page_text, 
		$next_page_text, 
		$first_page_text, 
		$last_page_text ,$pager_url_last); 
	 		
	$result = my_query($query ." LIMIT ".$kgPagerOBJ->start.", ".$kgPagerOBJ->per_page); 	
	$row = array(); 
	$i = ($current_page  - 1 ) * 25; 
	while( $ey =my_fetch_array($result) ){

		$periode_property = array(
			'href'=>'index.php?com='.$_GET['com'].'
				&task=list_periode
				&rapel_id='.$ey['rapel_id'],
			'title'=>'Periode',
		);
		$periode_button = button_icon( 'b_calendar.png' , $periode_property  );		
		
		$detail_property = array(
			'href'=>'index.php?com='.$_GET['com'].'
				&task=list_komponen
				&rapel_id='.$ey['rapel_id'],
			'title'=>'Komponen',
		);
		$detail_button = button_icon( 'b_props.png' , $detail_property  );
		
		$referensi=get_referensi( $ey['sumber_id'],$ey['ref_id']) ;
		$sumbers=my_get_data_by_id('rapel_sumber','sumber_id', $ey['sumber_id']) ;
		$bulan=get_count_rapel( $ey['rapel_id'] ) ;
		if( $bulan > 0){
			$delete_button = button_icon( 'b_drop_off.png' , $deleteproperty  );		
		}else{
			$deleteproperty = array(
				'href'=>'javascript:; ',
				'onclick'=>'javascript:confirmDelete('.$ey['rapel_id'].');',
				'title'=>'Delete'
			);
			$delete_button = button_icon( 'b_drop.png' , $deleteproperty  );		
		}
		
		$row[] = array(
			'sumber_trans'=>$sumbers['nama_sumber'],
			'referensi'=>$referensi,
			'bulan'=>position_text_align($bulan.' bulan','right'),
			' v'=>position_text_align($detail_button.' '.$periode_button.' '.$delete_button,'right'),
		);
	}
	$datas = table_rows($row);

	$paging = $kgPagerOBJ ->showPaging();
	return table_builder($header , $datas ,  3 , false , $paging);
}


/*  
==================================================================
2. PERIODE
==================================================================
*/

function list_periode($rapel_id){

	my_set_code_js('
		function confirmDelete(id){
			var t = confirm(\'Yakin akan menghapus data ?\');
			if(t){
				location.href=\'index.php?com='.$_GET['com'].'&task=delete_rapel_periode&id=\'+id;
			}
			return false;
		}
	');

	$header = array(
		'#'=>array('style'=>'text-align:center;border-bottom:2px solid;width:5%'),  
		'Periode Gaji'=>array('style'=>'border-bottom:2px solid;width:45%'),  
		'Periode Bayar'=>array('style'=>'border-bottom:2px solid;width:45%'),  
		' '=>array('style'=>'text-align:right;border-bottom:2px solid;width:5%'),  
	);
	
	$query = "
			SELECT * FROM pr_rapel_periode a
			INNER JOIN pr_periode b ON b.periode_id=a.periode_gaji  
			WHERE a.rapel_id={$rapel_id} 
			ORDER BY a.periode_gaji
		";	

	$result = my_query($query );
	$row = array(); 
	$i=0 ;
	while($ey = my_fetch_array($result)){
		$i++ ;

		$editproperty = array(
			'href'=>'index.php?com=pr_rapel&task=rapel_periode_create
				&rapel_id='.$rapel_id.'
				&id='.$ey['rapel_periode_id'],
			'rel'=>'facebox',
			'title'=>'Edit'
		);
		$edit_button = button_icon( 'b_edit.png' , $editproperty  );
		
		$deleteproperty = array(
			'href'=>'javascript:; ',
			'onclick'=>'javascript:confirmDelete('.$ey['rapel_periode_id'].');',
			'title'=>'Delete'
		);
		$delete_button = button_icon( 'b_drop.png' , $deleteproperty  );
		
		$row[] = array(
			'#'=>  position_text_align ($i ,'center'),      
			'periode_gaji'=> date('m-Y',strtotime($ey['tanggal'])),
			'periode_bayar'=> date('m-Y',strtotime($ey['periode_bayar'])),
			'operasi'=> position_text_align( $edit_button .' '.$delete_button, 'right'),
		);
	}

	$rapels=my_get_data_by_id('pr_rapel','rapel_id',$rapel_id) ;
	$referensi=get_referensi( $rapels['sumber_id'],$rapels['ref_id']) ;
	$sumbers=my_get_data_by_id('rapel_sumber','sumber_id', $rapels['sumber_id']) ;

	$menuontop = array(  
		'Back' => array('onclick'=>'javascript:location.href=\'index.php?com=pr_rapel\''),
		'Tambah Data'=> array('onclick'=> 'javascript:jQuery.facebox({ ajax: \'index.php?com='.$_GET['com'].'&task=rapel_periode_create&rapel_id='.$rapel_id.'&id=0\' })')
		);	
	$datas = table_rows($row);  

	$view  = form_header( "..." , "..."  );
	$view .=form_field_display( '<span class="label_form">'.$sumbers['nama_sumber'] .'</span>'   , "<b>Sumber Transaksi</b>"    ) ;
	$view .=form_field_display( '<span class="label_form">'.  $referensi .'</span>'   , "<b>Referensi</b>"    ) ;
	$view  .= form_footer(  );
	
	$printmenu = additional_menu_on_list( $menuontop , '');
	return  $view.$printmenu.table_builder($header , $datas ,  6 , false   );	
}

function form_rapel_periode_create($rapel_id, $id = 0){
	$view = form_header( "periode" , "periode"  );
 	$fields = my_get_data_by_id('pr_rapel_periode','rapel_periode_id',$id);

	$datas = array();
	$query_golongan = "SELECT * FROM pr_periode WHERE periode_id<".get_periode_gaji()." ORDER BY periode_id";
	$re = my_query($query_golongan);
	while($row = my_fetch_array($re) ){
		$datas[$row['periode_id']] = date('m-Y',strtotime($row['tanggal']));
	}
	$temp = array(
		'name'=>'periode_gaji',
		'id'=>'periode_gaji',
		'value'=>isset($_POST['periode_gaji']) ? $_POST['periode_gaji'] : $fields['periode_gaji'],
	);
	$form_temp = form_dropdown($temp , $datas);
	$view .= form_field_display( $form_temp , "Periode Gaji" );

	$month =date('m');
	$year =date('Y');
	if($id>0){
		$tanggal=$fields['periode_bayar'] ;
		$month = (int) date('m' , strtotime($tanggal));
		$year = (int) date('Y' , strtotime($tanggal));	
	}

	$bulans  = array(
		'01'=>'01', 
		'02'=>'02', 
		'03'=>'03', 
		'04'=>'04', 
		'05'=>'05', 
		'06'=>'06', 
		'07'=>'07', 
		'08'=>'08', 
		'09'=>'09', 
		'10'=>'10', 
		'11'=>'11', 
		'12'=>'12', 
	);
	$temp = array(
		'name'=>'bulan',
		'value'=>isset($_POST['bulan']) ? $_POST['bulan']: $month
	);
	$form_bulan = form_dropdown( $temp,$bulans);	
	$temp = array(
		'name'=>'tahun',
		'size'=>5,
		'value'=>isset($_POST['tahun']) ? $_POST['tahun']: $year
	); 
	$form_tahun = form_dynamic($temp );	
	$view .= form_field_display( $form_bulan.' '. $form_tahun  , "Periode Bayar"    );
	
	$submit = array(
		'value' => ( $id ==0 ? ' Simpan ' :'  Update  '),
		'name' => 'simpan', 
		'type'=>'submit','class'=>'main_button'
	);
	$form_submit= form_dynamic($submit); 
	$view .= form_field_display( $form_submit  , "&nbsp;" ,  "" );
	$view .= form_footer( );
	return $view;
} 
	 
function rapel_periode_submit($rapel_id, $id){

	$tanggal = $_POST['tahun'].'-'.$_POST['bulan'].'-01'; 
	$datas = array(
		'rapel_id'=>my_type_data_int($rapel_id),	
		'periode_gaji'=>my_type_data_int( $_POST['periode_gaji'] ),	
		'periode_bayar'=> my_type_data_str($tanggal),	
	);
	
	if($id > 0){
		my_update_record('pr_rapel_periode' ,'rapel_periode_id' , $id , $datas);
	}else{
		 $id=my_insert_record('pr_rapel_periode' , $datas);
	}
	kalkulasi_rapel_per_periode(  $id ) ;
	return true;
} 

function rapel_periode_validate($rapel_id, $id){
	$errsubmit = false;
	$err = array();
	 
	$periode_id =  trim($_POST["periode_gaji"]); 
	$query="SELECT periode_gaji FROM pr_rapel_periode
		WHERE periode_gaji=".$periode_id.
		" AND rapel_periode_id<>".$id ; 

	if (my_num_rows( my_query($query)) >0){
		$errsubmit = true;
		$err[] = "Periode Gaji sudah ada";	
	}
    
	if( $errsubmit){
		return $err;
	}
	return $errsubmit;
}

function delete_rapel_periode($id){
	$query = "DELETE FROM pr_rapel_bayar WHERE rapel_periode_id ={$id} ";
	my_query($query);
	$query = "DELETE FROM pr_rapel_periode WHERE rapel_periode_id ={$id} ";
	return my_query($query);
}	
	

/*  
==================================================================
3. KOMPONEN
==================================================================
*/
function total_rapel_gapok($rapel_id){
	$query = "SELECT SUM(nominal) AS anom FROM pr_rapel_komponen_karyawan WHERE komponen_id = 0 
		AND rapel_id = {$rapel_id}";
	$result = my_query($query);
	$rpw = my_fetch_array($result);
	return $rpw['anom'];
}
function list_komponen($rapel_id){

	my_set_code_js('
		function confirmDelete(id){
			var t = confirm(\'Yakin akan menghapus data ?\');
			if(t){
				location.href=\'index.php?com='.$_GET['com'].'&task=delete_rapel_komponen&id=\'+id;
			}
			return false;
		}
	');

	$header = array(
		'#'=>array('style'=>'text-align:right;border-bottom:2px solid;width:5%'),  
		'Komponen'=>array('style'=>'border-bottom:2px solid;width:75%'),  
		'Nilai '=>array('style'=>'text-align:right;border-bottom:2px solid;width:15%'),
		' '=>array('style'=>'text-align:right;border-bottom:2px solid;width:5%'),  
	);
	
	$query = "
			SELECT *  FROM pr_rapel_komponen a
			INNER JOIN pr_komponen_gaji b ON b.komponen_gaji_id=a.komponen_id  
			WHERE a.rapel_id={$rapel_id} 
			ORDER BY a.komponen_id
		";	

	$result = my_query($query );
	$row = array(); 
	$i=1 ;
	$deleteproperty = array(
			'href'=>'javascript:; ',
			'onclick'=>'javascript:alert(\'Can not delete\')',
			'title'=>'Delete'
	);
	$delete_button = button_icon( 'b_drop.png' , $deleteproperty  );
	$rapelexcelproperty = array(
		'href'=>'index.php?com=pr_rapel&rapel_id='.$rapel_id.'&task=list_komponen_detail&komponen_id=0', 
		'title'=>'Detail'
	);
	$rapel_button = button_icon( 'b_browse.png' , $rapelexcelproperty  );
	$row[] = array(
			'#'=>  position_text_align ($i ,'right'),      
			'komponen'=> 'Gaji pokok' ,
			   
			'hasil'=>  position_text_align( rp_format(total_rapel_gapok($rapel_id))  ,'right'),
			'operasi'=> position_text_align( $rapel_button .' '.$delete_button, 'right'),
		);
	while($ey = my_fetch_array($result)){
		$i++ ;

		$deleteproperty = array(
			'href'=>'javascript:; ',
			'onclick'=>'javascript:confirmDelete('.$ey['rapel_komponen_id'].');',
			'title'=>'Delete'
		);
		$delete_button = button_icon( 'b_drop.png' , $deleteproperty  );
		/*
		$rapelexcelproperty = array(
			'href'=>'index.php?com=pr_rapel&rapel_id='.$rapel_id.'&task=excel_rapel&komponen_id='.$ey['komponen_gaji_id'], 
			'title'=>'Download excel'
		);
		$rapel_button = button_icon( 'b_browse.png' , $rapelexcelproperty  );
		*/
		$rapelexcelproperty = array(
			'href'=>'index.php?com=pr_rapel&rapel_id='.$rapel_id.'&task=list_komponen_detail&komponen_id='.$ey['komponen_gaji_id'], 
			'title'=>'Detail'
		);
		$rapel_button = button_icon( 'b_browse.png' , $rapelexcelproperty  );
		$rapel_nominal = total_nominal_rapel_komponen($rapel_id , $ey['komponen_gaji_id']);
		$row[] = array(
			'#'=>  position_text_align ($i ,'right'),      
			'komponen'=> $ey['nama_komponen_gaji']  ,
			   
			'hasil'=>  position_text_align( rp_format($rapel_nominal)  ,'right'),
			'operasi'=> position_text_align( $rapel_button .' '.$delete_button, 'right'),
		);
	}

	$rapels=my_get_data_by_id('pr_rapel','rapel_id',$rapel_id) ;
	$referensi=get_referensi( $rapels['sumber_id'],$rapels['ref_id']) ;
	$sumbers=my_get_data_by_id('rapel_sumber','sumber_id', $rapels['sumber_id']) ;

	$menuontop = array(  
		//'Kembali' => array('onclick'=>'javascript:location.href=\'index.php?com=pr_rapel\''), 
		'Excel' => array('onclick'=>'javascript:location.href=\'index.php?com=pr_rapel&task=excel_list_komponen&rapel_id='.$rapel_id.'\''), 
		'Kalkulasi' =>  array('onclick'=>'javascript: jQuery.facebox({ ajax: \'index.php?com='.$_GET['com'].'&task=loading_rapel&rapel_id='.$rapel_id.'\' });'),
		//'Kalkulasi' => array('onclick'=>'javascript:location.href=\'index.php?com=pr_rapel&task=kalkulasi&rapel_id='.$rapel_id.'\''), 
		'Tambah data'=> array('onclick'=> 'javascript:jQuery.facebox({ ajax: \'index.php?com='.$_GET['com'].'&task=rapel_komponen_create&rapel_id='.$rapel_id.'&id=0\' })'),
		'Auto' => array('onclick'=>'javascript:location.href=\'index.php?com=pr_rapel&task=insert_komponen_auto&rapel_id='.$rapel_id.'\''), 
	);	
	$datas = table_rows($row);  

	$view  = form_header( "..." , "..."  );
	$view .=form_field_display( '<span class="label_form">'.$sumbers['nama_sumber'] .'</span>'   , "<b>Sumber Transaksi</b>"    ) ;
	$view .=form_field_display( '<span class="label_form">'.  $referensi .'</span>'   , "<b>Referensi</b>"    ) ;
	$view  .= form_footer(  );
	
	$printmenu = additional_menu_on_list( $menuontop , '<input type="button" value="Kembali" class="main_button" onclick="javascript:location.href=\'index.php?com=pr_rapel\'" />');
	return  $view.$printmenu.table_builder($header , $datas ,  6 , false   );	
}

function total_nominal_rapel_komponen($rapel_id , $komponen_id){
	$query = "SELECT sum(nominal) AS anom FROM pr_rapel_komponen_karyawan WHERE rapel_id ={$rapel_id} AND komponen_id = {$komponen_id}";
	$result = my_query($query);
	$row =my_fetch_array($result);
	return (int) $row['anom'];
}


function excel_list_komponen($rapel_id){
	$header = array( 
		'Komponen'=>array(),       
		'Nilai'=>array()  
	);  
	
	$query = "
			SELECT * FROM pr_rapel_komponen a
			INNER JOIN pr_komponen_gaji b ON b.komponen_gaji_id=a.komponen_id  
			WHERE a.rapel_id={$rapel_id} 
			ORDER BY a.komponen_id
		";	

	$result = my_query($query );
	$row = array();
	$rapel_nominal = total_nominal_rapel_komponen($rapel_id , 0);
	$row[] = array(      
		'komponen'=> 'Gaji pokok' , 
		'hasil'=>   $rapel_nominal 
	);
	while($ey = my_fetch_array($result )){
		$rapel_nominal = total_nominal_rapel_komponen($rapel_id , $ey['komponen_gaji_id']);
		$row[] = array(      
			'komponen'=> $ey['nama_komponen_gaji']  , 
			'hasil'=>   $rapel_nominal 
		);

	}
	$datas = table_rows_excel($row); 
	return table_builder_excel($header , $datas ,2 ,false ); 
}

function form_rapel_komponen_create($rapel_id, $id = 0){
	$view = form_header( "komponen" , "komponen"  );
 	$fields = my_get_data_by_id('pr_rapel_komponen','rapel_komponen_id',$id);

	$datas = array();
	$query_golongan = "SELECT * FROM pr_komponen_gaji ORDER BY komponen_gaji_id";
	$re = my_query($query_golongan);
	while($row = my_fetch_array($re) ){
		$datas[$row['komponen_gaji_id']] =$row['nama_komponen_gaji'];
	}
	$temp = array(
		'name'=>'komponen_id',
		'id'=>'komponen_id',
		'value'=>isset($_POST['komponen_id']) ? $_POST['komponen_id'] : $fields['komponen_id'],
	);
	$form_temp = form_dropdown($temp , $datas);
	$view .= form_field_display( $form_temp , "Komponen" );
	
	$submit = array(
		'value' => ( $id ==0 ? ' Simpan ' :'  Update  '),
		'name' => 'simpan', 
		'type'=>'submit','class'=>'main_button'
	);
	$form_submit= form_dynamic($submit); 
	$view .= form_field_display( $form_submit  , "&nbsp;" ,  "" );
	$view .= form_footer( );
	return $view;
} 
	 
function rapel_komponen_submit($rapel_id, $id){
	$datas = array(
		'rapel_id'=>my_type_data_int($rapel_id),	
		'komponen_id'=>my_type_data_int( $_POST['komponen_id'] ),	
	);
	
	if($id > 0){
		 my_update_record('pr_rapel_komponen' ,'rapel_komponen_id' , $id , $datas);
	}else{
		my_insert_record('pr_rapel_komponen' , $datas);
	}	
	return true;
} 

function rapel_komponen_validate($rapel_id, $id){
	$errsubmit = false;
	$err = array();
	 
	$komponen_id =  trim($_POST["komponen_id"]); 
	$query="SELECT komponen_id FROM pr_rapel_komponen
		WHERE rapel_id = ".$rapel_id." AND komponen_id=".$komponen_id.
		" AND rapel_komponen_id<>".$id ; 
 
	if (my_num_rows( my_query($query)) >0){
		$errsubmit = true;
		$err[] = "Komponen sudah ada";	
	}
    
	if( $errsubmit){
		return $err;
	}
	return $errsubmit;
}

function delete_rapel_komponen($id){
	$query = "DELETE FROM pr_rapel_komponen WHERE rapel_komponen_id ={$id} ";
	my_query($query);
	return true;
}	


function insert_komponen_auto($rapel_id){
	$query = "DELETE FROM pr_rapel_komponen WHERE rapel_id={$rapel_id}";
	my_query($query);	
	$query = "SELECT komponen_gaji_id FROM pr_komponen_gaji WHERE formula like '%[GAPOK]%' 
			ORDER BY nama_komponen_gaji
		";
	$res_komponen = my_query($query );	
	while($ey_komponen = my_fetch_array($res_komponen) ){
		$datas = array(
			'rapel_id'=>my_type_data_int($rapel_id),	
			'komponen_id'=>my_type_data_int( $ey_komponen['komponen_gaji_id'] ),	
		);
		my_insert_record('pr_rapel_komponen' , $datas);
	}
	return true;		
} 



function list_komponen_rapel_detail($komponen_id , $rapel_id){
	$komponens=my_get_data_by_id('pr_komponen_gaji','komponen_gaji_id',$komponen_id);
	$header = array(
		'NIK'=>array('style'=>'text-align:center;border-bottom:2px solid;width:10%'),  
		'Nama'=>array('style'=>'text-align:left;border-bottom:2px solid;width:60%'),  
		'Nominal'=>array('style'=>'text-align:right;border-bottom:2px solid;width:30%'),  
	);
	$query = "SELECT karyawan_id,	SUM(nominal) AS nom
		FROM pr_rapel_komponen_karyawan 
		WHERE rapel_id={$rapel_id} 
		AND komponen_id={$komponen_id} 
		GROUP BY karyawan_id
		ORDER BY karyawan_id"
	; 
	$result = my_query($query);
	$total_records = my_num_rows($result );
	$scroll_page =5;  
	$per_page =25;  
	$current_page = isset($_GET['page']) ? (int) $_GET['page'] : 1 ; 
	if($current_page < 1){
		$current_page = 1;
	}		 
	$pager_url  ="index.php?com={$_GET['com']}&task={$_GET['task']}&rapel_id={$_GET['rapel_id']}&field={$_GET['field']}
	&komponen_id={$_GET['komponen_id']}&page=";	 
	$inactive_page_tag = 'style="padding:4px;background-color:#BBBBBB"';  
	$previous_page_text = ' Mundur '; 
	$next_page_text = ' Maju ';  
	$first_page_text = ' Awal '; 
	$last_page_text = ' Akhir ';
	
	$kgPagerOBJ = new kgPager();
	$kgPagerOBJ->pager_set(
		$pager_url, 
		$total_records, 
		$scroll_page, 
		$per_page, 
		$current_page, 
		$inactive_page_tag, 
		$previous_page_text, 
		$next_page_text, 
		$first_page_text, 
		$last_page_text ,$pager_url_last); 
				
	$result = my_query($query ." LIMIT ".$kgPagerOBJ->start.", ".$kgPagerOBJ->per_page); 	
	$row = array(); 
	$i = ($current_page  - 1 ) * 25; 
	while($ey = my_fetch_array($result)){
		$karyawan_temp=$ey['karyawan_id'];
		$karyawan = loaddata_karyawan($ey['karyawan_id']);
		$row[] = array(
			'nik'=>position_text_align ($karyawan['nik'] ,'center'),    
			'gd'=>  $karyawan['nama_gelar'] ,  
			'nominal'=>  position_text_align (rp_format($ey['nom']) ,'right'),      
		); 
	}
	$datas = table_rows($row);
	$paging = $kgPagerOBJ ->showPaging();	
	$view  = form_header( "..." , "..."  ); 
	$view .= form_field_display( '<span class="label_form"> '.$komponens['nama_komponen_gaji'].'</span>'   , "<b>Komponen</b>"    ); 
	
	//if($komponens['model_entry'] =='1'){ 
	//	$menuontop = array(  
	//		'Upload' =>   array('onclick'=>'javascript: jQuery.facebox({ ajax: \'index.php?com='.$_GET['com'].'&task=rapel_komponen_upload&rapel_id='.$rapel_id.'&komponen_id='.$komponen_id.'\' });'), 
	//		'Excel' => array('onclick'=>'javascript:location.href=\'index.php?com='.$_GET['com'].'&rapel_id='.$rapel_id.'&task=excel_rapel&komponen_id='.$komponen_id.'\''),
	//		'Back' => array('onclick'=>'javascript:location.href=\'index.php?com='.$_GET['com'].'&rapel_id='.$rapel_id.'&task=list_komponen\''),
	//	);
	//} else {
		$menuontop = array(  
			//'Proses' => array('onclick'=>'javascript:location.href=\'index.php?com='.$_GET['com'].'&rapel_id='.$rapel_id.'&task=proses_rinci_komponen&komponen_id='.$komponen_id.'\''),
			//'Proses' =>  array('onclick'=>'javascript: jQuery.facebox({ ajax: \'index.php?com='.$_GET['com'].'&task=loading_rapel\' });'),
			'Except' => array('onclick'=>'javascript: jQuery.facebox({ ajax: \'index.php?com='.$_GET['com'].'&task=rapel_periode_create&rapel_id='.$rapel_id.'&komponen_id='.$komponen_id.'\' });'),
			'Excel' => array('onclick'=>'javascript:location.href=\'index.php?com='.$_GET['com'].'&rapel_id='.$rapel_id.'&task=excel_rapel&komponen_id='.$komponen_id.'\''),
			'Back' => array('onclick'=>'javascript:location.href=\'index.php?com='.$_GET['com'].'&rapel_id='.$rapel_id.'&task=list_komponen\''),
		);
	//}
	
	$printmenu = additional_menu_on_list( $menuontop , '');
	return  $view.$printmenu.table_builder($header , $datas ,  6 , false , $paging  );
}


function rapel_proses_komponen( $rapel_id){
  
	my_query("DELETE FROM pr_rapel_komponen_karyawan WHERE rapel_id = {$rapel_id}");
	
	$query_check_max = "SELECT MAX(pr_rapel_komponen_karyawan_id) as maximu FROM pr_rapel_komponen_karyawan  ";
	$result_check_max = my_query($query_check_max);
	$row_check_max = my_fetch_array($result_check_max);
	$newid = $row_check_max['maximu'] + 1;
	my_query("ALTER TABLE  `pr_rapel_komponen_karyawan` AUTO_INCREMENT = {$newid}");
	
	$rapels = get_count_rapel($rapel_id);
	$periode_gaji = get_periode_gaji();
	
	$komponens = listing_rapel_to_load($rapel_id);
	$query = "SELECT * FROM pr_periode WHERE periode_id < {$periode_gaji} ORDER BY periode_id  DESC LIMIT {$rapels}"; 

	$result = my_query($query);
	while($row = my_fetch_array($result) ){//var_dump($komponen_id); exit;
		$query2 = "
			SELECT * FROM karyawan a 
			WHERE a.karyawan_id NOT IN (select karyawan_id FROM karyawan_disable)
			AND a.karyawan_id NOT IN (select karyawan_id FROM pemberhentian) 		
		";
		$result2 = my_query($query2);
		$periode_id = $row['periode_id'];
		while($row2 = my_fetch_array($result2)){
			$karyawan_id = $row2['karyawan_id'];
			//GAJI RAPEL
			$nominal_rapel_gaji = get_gapok_rapel($karyawan_id ,  $periode_gaji  );
				$datas_rapel_gaji = array(
					'rapel_id'	=>my_type_data_int($rapel_id),
					'periode_prev_id'=>my_type_data_int($periode_id),
					'komponen_id'=>my_type_data_int(0),
					'karyawan_id'=>my_type_data_int($karyawan_id),
					'nominal'=>my_type_data_str(round($nominal_rapel_gaji) ),
				);  
			
				my_insert_record( 'pr_rapel_komponen_karyawan' , $datas_rapel_gaji);
			//GAJI RAPEL
			foreach($komponens as $komponen_id => $komp){
				
				if(get_model_entry_komponen($komponen_id ) == '1'){ 
						$nominal = hasil_komponen($komponen_id , 0, $karyawan_id) - hasil_komponen($komponen_id , $periode_id , $karyawan_id);
						$datas = array(
							'rapel_id'	=>my_type_data_int($rapel_id),
							'periode_prev_id'=>my_type_data_int($periode_id),
							'komponen_id'=>my_type_data_int($komponen_id),
							'karyawan_id'=>my_type_data_int($karyawan_id),
							'nominal'=>my_type_data_str(round($nominal) ),
						); 
						if( $nominal <> 0 )
						my_insert_record( 'pr_rapel_komponen_karyawan' , $datas);
				}else{
					if(trim($komp) <> ''){
						$strr = formula_rapel_umum($rapel_id , $komp);
						eval("\$hasil_type_entry  =  ".  $strr .";" ); 
					}
				}
			}
		}
	}
	return true;
}


function hasil_komponen($komponen_id , $periode_id , $karyawan_id){
	$query = "SELECT kalkulasi FROM pr_gaji_komponen 
			WHERE periode_id = {$periode_id} AND karyawan_id = {$karyawan_id} 
			AND komponen_id = {$komponen_id}";
	$result = my_query($query);
	$row = my_fetch_array($result);
	return ( $row['kalkulasi'] < 0 )  ? (-1) * $row['kalkulasi']:$row['kalkulasi'] ;
}


function get_model_entry_komponen($komponen_id ){
	$query = "SELECT model_entry FROM pr_komponen_gaji WHERE komponen_gaji_id = {$komponen_id}";
	$res = my_query($query);
	$row = my_fetch_array($res);
	return $row['model_entry'];
}

function listing_rapel_to_load($rapel_id){
	$query = "
			SELECT * FROM pr_rapel_komponen a
			INNER JOIN pr_komponen_gaji b ON b.komponen_gaji_id=a.komponen_id  
			WHERE a.rapel_id={$rapel_id} 
			ORDER BY a.komponen_id
		";	

	$result = my_query($query );
	$datas = array();
	while($row = my_fetch_array($result) ){
		$datas[$row['komponen_id']] = $row['formula_rapel'];
	}
	return $datas;
}


/*  
==================================================================
4. USER DEFINE FUNCTION
==================================================================
*/

function get_referensi($sumber_id,$ref_id){

	$referensi=' ' ;
	if( $sumber_id==1 ){
		$refs=my_get_data_by_id('pr_kenaikan_gaji','kenaikan_gaji_id',$ref_id ) ;
		$referensi='No. SK :'.$refs['sk_no'].' Periode : '.date("m-Y", strtotime($refs['tanggal'] ." 00:00:00" ) );
	}elseif( $sumber==2 ){
	}
	return $referensi;
		
}		

function insert_rapel($sumber_id, $ref_id){
	$id=get_rapel_id($sumber_id,$ref_id) ;
	$datas = array(
		'sumber_id'=> my_type_data_int($sumber_id),
		'ref_id'=> my_type_data_int($ref_id),
	);
	if( $id > 0){
	}else{		
		$id=my_insert_record( 'pr_rapel' , $datas );	
	}
	return true ;
}

 
function reset_rapel($sumber_id, $ref_id){
	$id=get_rapel_id($sumber_id,$ref_id) ;
	$query = "DELETE FROM pr_rapel WHERE rapel_id ={$id} ";
	my_query($query);

	$query = "DELETE FROM pr_rapel_komponen WHERE rapel_id={$id}";
	my_query($query);	
	
	$query = "SELECT * FROM pr_rapel_periode WHERE rapel_id ={$id} ";
	$result = my_query($query) ;
	while( $ey =my_fetch_array($result) ){
		$query = "DELETE FROM pr_rapel_bayar WHERE rapel_periode_id={$ey['rapel_periode_id']}";
		my_query($query);		
	}
	$query = "DELETE FROM pr_rapel_periode WHERE rapel_id ={$id} ";
	return my_query($query);
}
function reset_rapel_bayar($sumber_id, $ref_id){
	$id=get_rapel_id($sumber_id,$ref_id) ;
	$query = "SELECT * FROM pr_rapel_periode WHERE rapel_id ={$id} ";
	$result = my_query($query) ;
	while( $ey =my_fetch_array($result) ){
		$query = "DELETE FROM pr_rapel_bayar WHERE rapel_periode_id={$ey['rapel_periode_id']}";
		my_query($query);		
	}
	return true;
}


function get_rapel_id($sumber_id,$ref_id){
	$query = "SELECT rapel_id FROM pr_rapel WHERE sumber_id ={$sumber_id} AND ref_id={$ref_id}";
	$result= my_query($query);

	if( my_num_rows($result)>0 ){
		
		$ey= my_fetch_array($result) ;		
		return $ey['rapel_id'];
	}
	return 0 ;
}	

function get_count_rapel($id){
	$query = "SELECT COUNT(rapel_periode_id) as jumlah FROM pr_rapel_periode WHERE rapel_id  ={$id}";
	 
	$result= my_query($query);
	$ey= my_fetch_array($result) ;		
	return $ey['jumlah'];
}	

function kalkulasi_rapel( $id){
	$query = "SELECT rapel_periode_id FROM pr_rapel_periode WHERE rapel_id  ={$id}";
	$result= my_query($query);
	while($ey = my_fetch_array($result)){
		kalkulasi_rapel_per_periode($ey['rapel_periode_id']) ;
	}	
	return true;	
}	

function kalkulasi_rapel_per_periode( $rapel_periode_id ){
	$query = "DELETE FROM pr_rapel_bayar 
		WHERE rapel_periode_id={$rapel_periode_id}";	
	my_query($query);	//reset

	$periodes=my_get_data_by_id('pr_rapel_periode','rapel_periode_id',$rapel_periode_id) ;			
	$rapel_id=$periodes['rapel_id'] ;
	$periode_gaji=$periodes['periode_gaji'] ;
	$periode_bayar=$periodes['periode_bayar'] ;

	$rapels=my_get_data_by_id('pr_rapel','rapel_id',$rapel_id) ;			
	if( (int) $rapels['sumber_id']=1){
		$komponen_id=0 ; //Gaji
		$tipe='Gaji' ;
		$query = "
			SELECT karyawan_id,gaji_baru,gaji_lama
			FROM pr_kenaikan_gaji_karyawan
			WHERE kenaikan_gaji_id={$rapels['ref_id']} 
			ORDER BY karyawan_id
		";	
	}		
	$res_karyawan = my_query($query );
	while($ey_karyawan = my_fetch_array($res_karyawan) ){
		if( $komponen_id==0 ){
			$nominal_lama=$ey_karyawan['gaji_lama'] ;
			$nominal_baru=$ey_karyawan['gaji_baru'] ;
			$rapel=$nominal_baru-$nominal_lama ;
			$persen=0 ;
			if( $nominal_lama >0 ){
				$persen=$nominal_baru /$nominal_lama ;
			}
		}	
		$datas = array(
			'rapel_periode_id'=> my_type_data_int($rapel_periode_id),	
			'periode_bayar'=> my_type_data_str($periode_bayar),					
			'karyawan_id'=> my_type_data_int($ey_karyawan['karyawan_id']),					
			'tase'=> my_type_data_str($persen),	
			'rapel'=> my_type_data_str($rapel),				
		);
		my_insert_record( 'pr_rapel_bayar' , $datas );	
 		
	}
}	


function excel_rapel_report( $komponen_gaji , $rapel_id){
	 
	$header = array( 
		'NIK'=>array(),       
		'NAMA'=>array(),   
		'Rapel'=>array() 
	);  
	$periode_gaji_id  = get_periode_gaji();
	$query = "SELECT karyawan_id,	SUM(nominal) AS nom
		FROM pr_rapel_komponen_karyawan 
		WHERE rapel_id={$rapel_id} 
		AND komponen_id={$komponen_gaji} 
		GROUP BY karyawan_id
		ORDER BY karyawan_id"
	; 
	$result = my_query($query );	
	$row = array(); 
	$i = 0; 
	$factor = ( $periode_gaji_id - $last_periode_gaji );
	
	while($ey = my_fetch_array($result )){
		$i++; 
		$karyawan = loaddata_karyawan($ey['karyawan_id']);
		$row[] = array( 
			'nik'=>position_text_align( "'".sprintf('%07d',$karyawan['nik']), 'center'), 
			'nama'=>  $karyawan['nama'],  
			'baru'=>  $ey['nom']  , 
		//	'lama'=>    $nlama , 
		);
	}
	$datas = table_rows_excel($row); 
	return table_builder_excel($header , $datas ,4 ,false ); 	
}

function get_nilai_kalkulasi_prev_periode($karyawan_id , $periode_prev_id , $periode_gaji_id , $komponen_id){
   $factor = ( $periode_gaji_id - $periode_prev_id );
	$query = "SELECT * FROM pr_gaji_komponen a 
			INNER JOIN karyawan b ON b.karyawan_id=a.karyawan_id 
			WHERE a.kalkulasi > 0 AND  a.periode_id={$periode_prev_id} 
			AND a.karyawan_id={$karyawan_id} 
			AND a.komponen_id = {$komponen_id}
			ORDER BY b.nik";	 
	$result = my_query($query );
	$row = my_fetch_array($result);
	 
	return ( $factor * $row['kalkulasi'] );
}
 
function get_nilai_tase_rapel($karyawan_id,   $periode_gaji){ 
	$query = "SELECT  a.tase AS rapel_komponen 
			FROM  pr_rapel_bayar a
			INNER JOIN pr_rapel_periode b
			ON a.periode_bayar = b.periode_bayar
		WHERE a.karyawan_id={$karyawan_id} 
		AND b.periode_gaji={$periode_gaji} ";
	
	$res = my_query($query);
	$ey = my_fetch_array($res); 
	return ( $ey['rapel_komponen'] - 1);
}	

function form_rapel_komponen_upload($rapel_id){
	
	$view = form_header( "upload" , "upload"  );
	
	$file = array(
			'name'=>'file',
			'value'=>(isset($_POST['file'])? $_POST['file'] : $fields['file']),
			'id'=>'file' ,'size'=>'70',
			'type'=>'file'
	);
	$form_nominal = form_dynamic($file);
	$view .= form_field_display( $form_nominal , "File CSV" );
	
	$submit = array(
		'value' => ' Proses ',
		'name' => 'simpan', 
		'type'=>'submit','class'=>'main_button'
	);
	$form_submit= form_dynamic($submit); 
	
	$view .= form_field_display( $form_submit  , "&nbsp;" ,  "" );
	$view .= form_footer( );
	return $view;
}


function upload_rapel_page_submit($rapel_id){
	$dest ='files/csv/rapel_'.date('Ymd_his').'.csv';
	$ori = $_FILES['file']['tmp_name'];
	
	$rapels = get_count_rapel($rapel_id);
	$periode_gaji = get_periode_gaji();
	
	$query 	= "SELECT * FROM pr_periode WHERE periode_id < {$periode_gaji} ORDER BY periode_id  DESC LIMIT {$rapels}"; 
	$result = my_query($query);
	$row 	= my_fetch_array($result);
	$periode_id 	= $row['periode_id'];
	
	$upload = move_uploaded_file($ori , $dest); 
	if($upload){
		$handle = fopen($dest, "r"); 
		while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
			if(trim($data[0])<>'' && $data[1]<> ''){
			$karyawan_id =check_karyawan_by_nik(sprintf('%07d',$data[0]));
			stor_rapel_table($rapel_id,$periode_id , $_GET['komponen_id'], $karyawan_id, $data[1] );
			}
		}
		fclose($handle);
	}
	return $dest ;
}

function upload_rapel_form_validate(){
	$errsubmit = false;
	$err = array();
	
	$exts = array('csv','xls');
	$ext = end(explode("." , strtolower( $_FILES['file']['name'] ) ) );
	if( ! is_file($_FILES['file']['tmp_name']) ){
		$errsubmit = true;
		$err[] = "Tidak ada file yang disertakan";
	}
	elseif( ! in_array($ext , $exts)  ){
		$errsubmit = true;
		$err[] = "File tidak dikenali";
	}	
	
	if( $errsubmit){
		return $err;
	}
	return $errsubmit;
}


function stor_rapel_table($rapel_id,$periode_id , $komponen_id , $karyawan_id ,$nominal){
	$datas = array(
		'rapel_id'			=> my_type_data_int($rapel_id),
		'periode_prev_id'	=> my_type_data_int($periode_id),
		'komponen_id'		=> my_type_data_int($komponen_id),
		'karyawan_id'		=> my_type_data_int($karyawan_id),
		'nominal'			=> my_type_data_str($nominal),
	);
	
	return my_insert_record( 'pr_rapel_komponen_karyawan' , $datas );
}


function page_kalkulasi_rapel($rapel_id){
	my_set_code_js('
	$(document).ready(function() {
       	$(\'#onebar\').load(\'index.php?com='.$_GET['com'].'&rapel_id='.$rapel_id.'&task=kalkulasi_rapel_all&'.rand(0,9).'='.rand(0,99999).'\'); 
	});
	');
	return '<div id="onebar" style="width:100%;text-align:center;"><img src="components/system/jquery/facebox/loading.gif" /><br/>On processing!!!</div>';
}


function form_pengecualian($id=0){
	$fields = my_get_data_by_id('pr_penyesuaian','id',$id);
 
	my_set_file_js(
		array(
			'components/system/jquery/combomulti/jquery.chainedSelects.js',
			'components/system/js/calendar/calendarDateInput.js' 
		)
	);

	my_set_file_js(
		array(
			'components/system/jquery/autocomplete/jquery.autocomplete.js'  
		)
	);
	my_set_file_css(
		array(
				'components/system/jquery/autocomplete/jquery.autocomplete.css' 
			)
	);

	my_set_code_js('  
		function findValue(li) {
			if( li == null ) return alert("No match!"); 
			if( !!li.extra ) var sValue = li.extra[0]; 
			else var sValue = li.selectValue;
		}

		function selectItem(li) {
			findValue(li);
		}

		function formatItem(row) {
			return   row[0] ;
		}

		function lookupAjax(){
			var oSuggest = $("#nama_karyawan")[0].autocompleter;
			oSuggest.findValue(); 
			return false;
		}
		$(document).ready(function() {
			$("#nama_karyawan").autocomplete(
				"autocomplete_daftar_karyawan.php",
				{
					delay:10,
					minChars:2,
					matchSubset:1,
					matchContains:1,
					cacheLength:5,
					onItemSelect:selectItem,
					onFindValue:findValue,
					formatItem:formatItem,
					autoFill:true
				}
			);
			 
		});

		function checkName(name){
			$.get("check_karyawan_names.php", { nama: name  },
			   function(data){
				 if(data ==  \'0\' ){
					alert(\'Nama karyawan \'+ name+\' tidak ditemukan\nHarap diperiksa kembali\');
					$(\'#nama_karyawan\').val(\'\');
					return false;
				 } 
			   });
		}
	');	
	 
	$penyesuaian = array(
		'name'=>'penyesuaian',
		'id'=>'penyesuaian',
		'size'=>'15',
		'value'=>($fields ?   $fields['penyesuaian']   :'')
	);
	$form_penyesuaian = form_dynamic($penyesuaian); 
	
	$karyawan_data = loaddata_karyawan($fields['karyawan_id']);
	$jabatan = my_get_data_by_id('jabatan','jabatan_id', ($karyawan['jabatan_id']<>'' ? $karyawan['jabatan_id']: 0));
	$view  = form_header( "detail pegawai" , "cp"  );

	$karyawan = array(
		'name'=>'nama_karyawan',
		'value'=>(isset($_POST['nama_karyawan'])? $_POST['nama_karyawan'] : ( $fields['karyawan_id'] > 0 ? $karyawan_data['nik'].'/'.$karyawan_data['nama'] :'') ),
		'id'=>'nama_karyawan',
		'type'=>'textfield',
		'size'=>'45'
	);
	$form_karyawan = form_dynamic($karyawan);
	$view .= form_field_display( $form_karyawan  , "<b>NIK/Nama Kary.</b>"  );
	/*
	$checkKomponen = "SELECT * FROM pr_komponen_gaji ORDER BY tipe ASC";
	$cresult = my_query($checkKomponen);
	$optionKomponen = array();
	while( $row = my_fetch_array($cresult) ){ 	
		$optionKomponen[$row['komponen_gaji_id']] = $row['nama_komponen_gaji'];
	}
	$komponen = array(
		'name'=>'komponen_id',
		'value'=>(isset($_POST['komponen_id'])? $_POST['komponen_id'] :  $fields['komponen_id']	     ),
		'id'=>'komponen_id'
	);
	$view .= form_field_display( '<span class="label_form">'.form_dropdown($komponen , $optionKomponen).'</span>'   , "<b>Nama Komponen</b>"    ); 
	*/
	$view .= form_field_display(  $form_penyesuaian  , "<b>Nominal</b>"    );
 
	$submit = array(
		'value' => ( $id ==0 ? ' Simpan ' :'  Update  '),
		'name' => 'simpan', 
		'type'=>'submit','class'=>'main_button'
	);
	$form_submit= form_dynamic($submit); 
	
	$view .= form_field_display( $form_submit  , "&nbsp;" ,  "" );
	$view .= form_footer( );
	
	return $view;
}

function submit_pengecualian( $komponen_id , $rapel_id){
	$karyawan_id = check_karyawan_by_nik_nama($_POST['nama_karyawan']);
	$rapels = get_count_rapel($rapel_id);
	$periode_gaji = get_periode_gaji();
	
	$query 	= "SELECT * FROM pr_periode WHERE periode_id < {$periode_gaji} ORDER BY periode_id  DESC LIMIT {$rapels}"; 
	$result = my_query($query);
	$row 	= my_fetch_array($result);
	$periode_id 	= $row['periode_id'];
	
	 $query = "SELECT * FROM pr_rapel_komponen_karyawan 
		WHERE karyawan_id = {$karyawan_id}  
		AND komponen_id={$komponen_id}";
	 
	$result = my_query($query);
	if(my_num_rows($result) > 0){
		$query = "UPDATE pr_rapel_komponen_karyawan SET 
			nominal = '".$_POST['penyesuaian']."' 
			WHERE karyawan_id=".$karyawan_id." 
			AND rapel_id=".$rapel_id."
			AND komponen_id=".$komponen_id ;
		return my_query($query);	
	}
	 
	$datas = array(
		'rapel_id'	=>my_type_data_int($rapel_id),
		'periode_prev_id'=>my_type_data_int($periode_id ),
		'komponen_id'=>my_type_data_int($komponen_id),
		'karyawan_id'=>my_type_data_int($karyawan_id),
		'etest'=>my_type_data_str('Y'),
		'nominal'=>my_type_data_str($_POST['penyesuaian']),
	); 
	if( (int) $_POST['penyesuaian'] <> 0 )
	my_insert_record( 'pr_rapel_komponen_karyawan' , $datas);
}
